package com.lsl.musicplayer.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.io.IOException;
import java.util.List;

/**
 * author lishilin
 * date 2023/8/8 生日当天修改
 * desc 音乐服务类，负责后台播放音乐，利用广播更新activity的UI
 */
public class MusicService extends Service {

    private MediaPlayer mediaPlayer;
    private List<String> playList;
    private int currentMusicIndex;
    private boolean isStopMusic = false;
    private boolean isPlay = false;

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        musicListener();
        startPreNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case "ACTION_PLAY":
                    int index = intent.getIntExtra("index", 0);
                    if (index < playList.size()) {
                        currentMusicIndex = index;
                        startOrPauseMusic();
                    }
                    break;
                case "CHANGE_MUSIC":
                    int changeIndex = intent.getIntExtra("changeIndex", 0);
                    currentMusicIndex = changeIndex;
                    changeMusic();
                    break;
                case "ACTION_PAUSE":
                    pauseMusic();
                    break;
                case "ACTION_SET_PATH":
                    String path = intent.getStringExtra("musicPath");
                    playList.add(path);
                    int playIndex = intent.getIntExtra("playIndex", 0);
                    currentMusicIndex = playIndex;
                    prepareMusic();
                    break;
                case "INIT_MUSIC_LIST":
                    List<String> list = intent.getStringArrayListExtra("musicList");
                    playList = list;
                    break;
                case "CHANGE_PROCESS":
                    int process = intent.getIntExtra("process", 0);
                    if (mediaPlayer != null) {
                        mediaPlayer.seekTo(process);
                    }
                    break;
            }
        }
        return START_STICKY;
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private void startPreNotification() {
        Intent intent = new Intent(this, PreNotificationService.class);
        startService(intent);
    }

    /**
     * 监听音乐准备完毕
     */
    public void musicListener() {
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                playMusic();
                if (mediaPlayer.isPlaying()) {
                    isStopMusic = false;
                    isPlay = true;
                }
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (!isStopMusic && playList.size()>0) {
                    if (currentMusicIndex == playList.size() - 1) {
                        currentMusicIndex = 0;
                    } else {
                        currentMusicIndex++;
                    }
                    changeMusic();
                    Log.d("监听", "播放结束，自动播放下一曲");
                } else {
                    return;
                }
            }
        });
    }
    private void changeMusic() {
        if (playList == null || playList.size()==0){
            return;
        }
        //Uri uri = musicList.get(currentMusicIndex);
        String path = playList.get(currentMusicIndex);
        isStopMusic = true;
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        //延时任务
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
//                    mediaPlayer.setDataSource(getApplicationContext(), uri);
                    mediaPlayer.setDataSource(path);
                    mediaPlayer.prepareAsync();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 1000);
    }

    /**
     * 准备音乐
     */
    public void prepareMusic() {
        try {
            mediaPlayer.reset();
            //Uri musicPath = musicList.get(currentMusicIndex);
            String path = playList.get(currentMusicIndex);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playMusic() {
        int total = mediaPlayer.getDuration();
        Intent intent = new Intent("TOTAL_PROCESS");
        intent.putExtra("max", total);
        sendBroadcast(intent);
        Intent playIntent = new Intent("MUSIC_PLAY");
        mediaPlayer.start();
        isPlay = true;
        updateProcess();
        sendBroadcast(playIntent);
    }

    /**
     * 更新进度条
     */
    public void updateProcess() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isPlay) {
                    int currentProcess = mediaPlayer.getCurrentPosition();
                    Intent intent = new Intent("UPDATE_PROCESS");
                    intent.putExtra("process", currentProcess);
                    sendBroadcast(intent);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    private void pauseMusic() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPlay = false;
        }
    }

    /**
     * 通过发送广播的放视通知activity暂停或者播放音乐
     */
    private void startOrPauseMusic() {
        if (!mediaPlayer.isPlaying()) {
            Intent intent = new Intent("MUSIC_PLAY");
            mediaPlayer.start();
            if (mediaPlayer.isPlaying()){
                //重新启动线程去更新进度条
                isPlay = true;
                updateProcess();
                sendBroadcast(intent);
            }

        } else {
            Intent intent = new Intent("MUSIC_PAUSE");
            sendBroadcast(intent);
            mediaPlayer.pause();
            isPlay = false;
        }
    }

    private void stopMusic() {
        mediaPlayer.stop();
        mediaPlayer.reset();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopMusic();
        stopForeground(true);
        Intent intent = new Intent(this, PreNotificationService.class);
        stopService(intent);
        mediaPlayer.release();
    }
}